<template>
  <div class="container">
    <el-drawer
      v-model="isShow"
      :before-close="close"
      :destroy-on-close="true"
      :with-header="false"
      size="500px"
      ><div id="account-form-container">
        <el-card class="box-card" shadow="never" :body-style="{ border: 0 }">
          <template #header>
            <div class="clearfix">
              <span>创建活动</span>
            </div>
          </template>
          <div class="studentcrad">
            <el-form
              ref="activeRef"
              :model="active"
              :rules="saveActiveRule"
              label-width="80px"
            >
              <el-form-item label="活动名称" prop="activityName">
                <el-input
                  v-model="active.activityName"
                  placeholder="活动名称"
                  :readonly="!isCreate"
                ></el-input>
              </el-form-item>
              <el-form-item label="报名时间" prop="enrollTime">
                <el-date-picker
                  v-model="active.enrollTime"
                  format="YYYY-MM-DD HH:mm"
                  style="width: 100%"
                  type="datetimerange"
                  :readonly="!isCreate"
                  start-placeholder="报名开始时间"
                  end-placeholder="报名结束时间"
                  :default-time="defaultTime"
                  :disabledDate="disabledDate"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="活动时间" prop="activeTime">
                <el-date-picker
                  v-model="active.activeTime"
                  format="YYYY-MM-DD HH:mm"
                  style="width: 100%"
                  :readonly="!isCreate"
                  type="datetimerange"
                  start-placeholder="活动开始时间"
                  end-placeholder="活动结束时间"
                  :default-time="defaultTime"
                  :disabledDate="disabledDateActiveTime"
                >
                </el-date-picker>
              </el-form-item>

              <el-form-item label="活动内容" prop="content">
                <el-input
                  v-model="active.content"
                  :readonly="!isCreate"
                  :rows="4"
                  type="textarea"
                ></el-input>
              </el-form-item>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="活动分数" prop="score">
                    <el-input-number
                      v-model="active.score"
                      :disabled="!isCreate"
                      size="small"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="活动人数" prop="numberOfPeople">
                    <el-input-number
                      v-model="active.numberOfPeople"
                      :disabled="!isCreate"
                      size="small"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="活动模块" prop="activityBlock">
                <el-select
                  v-model="active.activityBlock"
                  placeholder="请选择活动模块"
                  :disabled="!isCreate"
                >
                  <el-option
                    v-for="(item, index) in baiyemoulds"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="活动海报" prop="picture">
                    <input type="text" hidden v-model="active.picture" />
                    <el-upload
                      v-if="isCreate"
                      class="upload-demo"
                      :http-request="upFile"
                      list-type="picture"
                      action=""
                      :limit="1"
                      :on-exceed="onExceed"
                      :on-remove="onRemove"
                      :fileList="fileList"
                      :before-upload="beforeUpload"
                    >
                      <el-button size="small" type="primary"
                        >点击上传</el-button
                      >
                      <template #tip>
                        <div class="el-upload__tip">只能上传 jpg/png 文件</div>
                      </template>
                    </el-upload>

                    <el-image
                      v-else
                      style="width: 100px; height: 100px"
                      :src="active.picture ? BaseUrl + active.picture : ''"
                      :preview-src-list="[BaseUrl + active.picture]"
                    ></el-image>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!isCreate">
                  <el-form-item label="加分码">
                    <el-image
                      style="width: 100px; height: 100px"
                      :src="active.qrCode ? BaseUrl + active.qrCode : ''"
                      :preview-src-list="[BaseUrl + active.qrCode]"
                    ></el-image>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item>
                <el-button
                  v-if="isCreate"
                  type="primary"
                  @click="onSaveAcitve"
                  style="margin-bottom: 30px"
                  :loading="loading"
                  >保存</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts">
import { reactive, ref, toRefs, unref, computed, watch } from "vue";
import { BaiyeService, Activity } from "@/api/baiye";
import { useStore } from "vuex";
import { ElMessage, ElNotification } from "element-plus";
import Code from "@/consts/common";
import { BaseUrl } from "@/utils/request";

export default {
  name: "activeDrawer",
  props: {
    isShow: {
      type: Boolean,
      default: false,
    },
    isCreate: {
      type: Boolean,
      default: true,
    },
    Id: {
      type: Number,
      default: {},
    },
    drawerClose: {
      type: Function,
    },
  },
  setup(props: any) {
    const activeRef = ref();
    const store = useStore();
    const active: Activity = { score: 2, numberOfPeople: 50 };
    let data = reactive({
      page: computed(() => store.state.Active.page),
      size: computed(() => store.state.Active.size),
      active: active,
      loading: false,
      BaseUrl: BaseUrl,
      fileList: [],
      saveActiveRule: {
        activityName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        enrollTime: [
          { required: true, message: "请选择活动报名时间", trigger: "blur" },
        ],
        activeTime: [
          {
            required: true,
            message: "请选择活动开始和结束时间",
            trigger: "blur",
          },
        ],
        activityBlock: [
          { required: true, message: "请选择活动模块", trigger: "blur" },
        ],
        score: [{ required: true, message: "请填写活动分数", trigger: "blur" }],
        numberOfPeople: [
          { required: true, message: "请填写活动人数", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请填写活动内容", trigger: "blur" },
        ],
        picture: [
          { required: true, message: "请上传活动封面", trigger: "blur" },
        ],
      },
      enrollTime: [],
      activeTime: [],
      baiyemoulds: [
        {
          value: 0,
          label: "博学",
        },
        {
          value: 1,
          label: "尽美",
        },
        {
          value: 2,
          label: "笃行",
        },
        {
          value: 3,
          label: "明德",
        },
      ],
      defaultTime: [
        new Date(2021, 1, 1, 8, 0, 0),
        new Date(2021, 2, 1, 12, 0, 0),
      ],
      close() {
        props.drawerClose();
        data.active = { score: 2, numberOfPeople: 50 };
        data.fileList = [];
      },
      onExceed() {
        ElNotification({
          showClose: true,
          title: "遇到错误",
          message: "请先移除已上传的文件再进行上传",
          type: "error",
        });
      },
      onRemove() {
        data.active.picture = "";
      },
      disabledDate(p: Date) {
        const item = new Date();
        // @ts-ignore
        if (item.format("yyyy-MM-dd") <= p.format("yyyy-MM-dd")) {
          return false;
        }
        return true;
      },
      getImgUrl(s: string): string {
        if ((s = "")) {
          return `${BaseUrl}/image/default.JPG`;
        }
        return `${BaseUrl}${s}`;
      },
      disabledDateActiveTime(p: Date) {
        if (data.active.enrollTime && data.active.enrollTime!.length > 0) {
          const item = new Date(data.active.enrollTime![1]);
          // @ts-ignore
          if (
            // @ts-ignore
            item.format("yyyy-MM-dd hh:mm:ss") < p.format("yyyy-MM-dd hh:mm:ss")
          ) {
            return false;
          }
          return true;
        } else {
          // @ts-ignore
          const item = new Date();
          if (
            // @ts-ignore
            item.format("yyyy-MM-dd hh:mm:ss") <=
            // @ts-ignore
            p.format("yyyy-MM-dd hh:mm:ss")
          ) {
            return false;
          }
          return true;
        }
      },
      upFile(param: any) {
        let fileObject = param.file;
        if (isImg(fileObject.name)) {
          let formData = new FormData();
          formData.append("file", fileObject);
          BaiyeService.upFile(formData).then((res) => {
            if (res.code == Code.CODE_SUCCESS) {
              data.active.picture = res.data;

              data.fileList = [
                {
                  // @ts-ignore
                  name: fileObject.name,
                  // @ts-ignore
                  url: `${BaseUrl}${data.active.picture}`,
                },
              ];
              ElMessage({
                showClose: true,
                message: "上传成功",
                type: "success",
              });
            } else {
              data.fileList = [];
            }
          });
        }
      },
      onSaveAcitve() {
        const activeRefq = unref(activeRef);
        if (!activeRefq) return;
        activeRefq.validate((valid: Boolean) => {
          if (valid) {
            const formatStr = "yyyy-MM-dd hh:mm";
            const item: Activity = {};
            item.score = data.active.score;
            item.numberOfPeople = data.active.numberOfPeople;
            item.picture = data.active.picture;
            item.activityBlock = data.active.activityBlock;
            item.content = data.active.content;
            item.activityName = data.active.activityName;
            item.enrollStartTime = format(
              formatStr,
              data.active.enrollTime![0].toString()
            );
            item.enrollEndTime = format(
              formatStr,
              data.active.enrollTime![1].toString()
            );
            item.startTime = format(
              formatStr,
              data.active.activeTime![0].toString()
            );
            item.endTime = format(
              formatStr,
              data.active.activeTime![1].toString()
            );
            data.loading = true;
            store.dispatch("Active/save", item).then((res) => {
              if (res.code == Code.CODE_SUCCESS) {
                props.drawerClose();
                data.active = { score: 2, numberOfPeople: 50 };
                ElMessage({
                  showClose: true,
                  message: "创建成功",
                  type: "success",
                });
                store.dispatch("Active/listActive", {
                  page: data.page,
                  size: data.size,
                });
              }
              data.loading = false;
            });
          }
        });
      },
      beforeUpload(param: any) {
        if (isImg(param.name)) {
          return true;
        } else {
          ElNotification({
            showClose: true,
            title: "遇到错误",
            message: "请先检查文件格式，文件格式只能是图片",
            type: "error",
          });
          return false;
        }
      },
    });
    const format = (formatStr: string, str: string): string => {
      // @ts-ignore
      return new Date(str).format(formatStr);
    };
    const isImg = (ext: string): boolean => {
      return ["png", "jpg", "jpeg", "bmp"].indexOf(ext.split(".")[1]) !== -1;
    };
    watch(
      () => props.isShow,
      (newValue: boolean, oldVlaue) => {
        if (newValue && props.Id != 0) {
          BaiyeService.getActiveById(props.Id).then((res) => {
            data.active = res.data;
            data.active.enrollTime = [
              new Date(data.active.enrollStartTime!),
              new Date(data.active.enrollEndTime!),
            ];
            data.active.activeTime = [
              new Date(data.active.startTime!),
              new Date(data.active.endTime!),
            ];
          });
        }
      }
    );
    return {
      ...toRefs(data),
      activeRef,
    };
  },
};
</script>

<style lang="less" scoped>
.container {
  margin: 0 15px;
  .studentcrad {
    padding: 0 20px 20px 0;
    margin-bottom: 20px;
    height: calc(100vh - 100px);
    overflow-y: auto;
  }
}
</style>

<style lang="less">
#account-form-container {
  .el-card {
    border: none;
  }
}
</style>
